
function showWalletCrombs() {
    var crombs = undefined;
    if (lastCrombs === undefined) {
        crombs = getCrombs();
    } else {
        crombs = lastCrombs;
    }
    var cards = new Array(0);
    cards.index = -1;
    if (crombs !== undefined) {
        cards = new Array(crombs.length);
        cards.index = 0;
    }
    for (var i = 0; i < cards.length; i++) {
        cards[i] = new Card(new CrombRenderer(crombs[i],"showWalletCrombs"));
    }
    if ($("#wallet").length > 0) {
        $("#wallet").remove();
    }
    var wallet = new Wallet("wallet", cards, "Crombz");
    wallet.init();
    showWarningNoGPS();
}
function showWalletEvents() {
    var events = getEventList();
    document.getElementById('mainview').innerHTML="<div id='wallet' style='height:95%;'><div id='map' style='height:80%;'></div>"+new EventPostRenderer(EventTypes).render()+"</div>";
    if (events !== undefined) {
        var locations = new Array(events.length);
        for (var i = 0; i < events.length; i++) {
            var e = events[i];
            locations[i] = [e.description, e.latitude, e.longitude, (i + 1),new EventRenderer(e).render()];
        }
        var map = new google.maps.Map(document.getElementById('map'), {
            zoom: 14,
            center: new google.maps.LatLng(gpsLatitude, gpsLongitude),
            mapTypeId: google.maps.MapTypeId.ROADMAP
        });
        var infowindow = new google.maps.InfoWindow();
        var marker, i;
        for (i = 0; i < locations.length; i++) {
            marker = new google.maps.Marker({
                position: new google.maps.LatLng(locations[i][1], locations[i][2]),
                map: map,
                title: locations[i][0],
                icon: "images/mapiconevent.png"
            });
            google.maps.event.addListener(marker, 'click', (function(marker, i) {
                return function() {
                    infowindow.setContent(locations[i][4]);
                    infowindow.open(map, marker);
                };
            })(marker, i));
        }

    }

//    var events = getEventList();
//    var cards = new Array(1);
//    if (events !== undefined) {
//        cards = new Array(events.length + 1);
//        for (var i = 0; i < cards.length; i++) {
//            cards[i] = new Card(new EventRenderer(events[i]));
//        }
//    }
//    cards[cards.length - 1] = new Card(new EventPostRenderer(EventTypes));
//    if ($("#wallet").length > 0) {
//        $("#wallet").remove();
//    }
//    var wallet = new Wallet("wallet", cards, "Eventz");
//    wallet.init();
    showWarningNoGPS();
}
function showWalletTags(userTag) {
    var tags = getTags(userTag);
    var cards = new Array(0);
    cards.index = -1;
    if (tags !== undefined) {
        cards = new Array(1);
        cards.index = 0;
        cards[0] = new Card(new TagRenderer(tags));
    }
    if ($("#wallet").length > 0) {
        $("#wallet").remove();
    }
    var title = "HashTagz";
    if (userTag !== undefined) {
        title += " (" + userTag + ")";
    }
    var wallet = new Wallet("wallet", cards, title);
    wallet.init();
    showWarningNoGPS();
}
function showWalletNews() {
    var news = getNews();
    var cards = new Array(1);
    if (news !== undefined) {
        cards = new Array(news.length + 1);
    }
    //First news is top crombers;
    cards[0] = new Card(new TopCrombersRenderer(getTopCrombers()));
    for (var i = 1; i < cards.length; i++) {
        cards[i] = new Card(new NewsRenderer(news[i - 1]));
    }
    if ($("#wallet").length > 0) {
        $("#wallet").remove();
    }
    var wallet = new Wallet("wallet", cards, "Newz");
    wallet.init();
}
function showWalletCrimes() {
    var crimes = getCrimeList(false);
    var crimesGlobal = getCrimeList(true);
    var cards = new Array(0);

    if (crimes !== undefined) {
        cards = new Array(2);
    } else if (crimesGlobal !== undefined) {
        cards = new Array(1);
    }
    if (crimes === undefined && crimesGlobal !== undefined) {
        cards[0] = new Card(new CrimesRenderer(crimesGlobal, true));
    } else if (crimes !== undefined) {
        cards[0] = new Card(new CrimesRenderer(crimes, false));
        cards[1] = new Card(new CrimesRenderer(crimesGlobal, true));
    }

    if ($("#wallet").length > 0) {
        $("#wallet").remove();
    }
    var wallet = new Wallet("wallet", cards, "Crime Report");
    wallet.init();
    showWarningNoGPS();
}
function showWalletCrombForm() {
    var cards = new Array(1);
    cards.index = 0;
    cards[0] = new Card(new CrombFormRenderer());
    if ($("#wallet").length > 0) {
        $("#wallet").remove();
    }
    var wallet = new Wallet("wallet", cards, "Post a Cromb");
    wallet.init();
    showWarningNoGPS();
}
function showWalletLoginForm() {
    var cards = new Array(1);
    cards[0] = new Card(new LoginRenderer());
    if ($("#wallet").length > 0) {
        $("#wallet").remove();
    }
    var wallet = new Wallet("wallet", cards, "Login");
    wallet.init();
}
function showWalletHelp() {
    var cards = new Array(2);
    cards.index = 0;
    cards[0] = new Card(new HelpPage1Renderer());
    cards[1] = new Card(new HelpPage2Renderer());
    if ($("#wallet").length > 0) {
        $("#wallet").remove();
    }
    var wallet = new Wallet("wallet", cards, "Help");
    wallet.init();
}
function showWalletGPSInfo() {
    var cards = new Array(1);
    cards.index = 0;
    cards[0] = new Card(new GPSInfoRenderer());
    if ($("#wallet").length > 0) {
        $("#wallet").remove();
    }
    var wallet = new Wallet("wallet", cards, "GPS Info");
    wallet.init();

}
function showWarning(text) {
    var existing = $("#warningview");
    if (existing.length > 0) {
        existing.remove();
    }
    var wait = $("<div id='warningview'>" + text + "</div>");
    $("#wallet").append(wait);
}
function showWarningNoGPS() {
    if (gpsLongitude === undefined) {
        var html = "";
        html += "<p class='title'>GPS is not providing data</p>";
        html += "<p class='content'>Make sure that your browser can access your GPS data.  Sometimes, it can take a few seconds";
        html += " for the GPS to initialize and provide your location...</p>";
        showWarning(html);
    }
}
function showWarningPleaseWait(text) {
    var html = "";
    html += "<p class='title'>Please wait...</p>";
    html += "<img width=75 height=75 src='images/loading.gif'/>";
    html += "<p class='content'>" + text + "</p>";
    showWarning(html);

}
function showWalletClosestCromb() {
    document.getElementById('mainview').innerHTML="<div id='wallet' style='height:95%;'></div>";
    if (lastCrombs === undefined) {
        lastCrombs = getCrombs();
    }
    if (lastCrombs !== undefined) {
        var crombs = lastCrombs;
        var locations = new Array(crombs.length);
        for (var i = 0; i < crombs.length; i++) {
            var c = crombs[i];
            locations[i] = [c.author, c.latitude, c.longitude, (i + 1),new CrombRenderer(c,"showWalletClosestCromb").render()];
        }
        var map = new google.maps.Map(document.getElementById('wallet'), {
            zoom: 14,
            center: new google.maps.LatLng(gpsLatitude, gpsLongitude),
            mapTypeId: google.maps.MapTypeId.ROADMAP
        });
        var infowindow = new google.maps.InfoWindow();
        var marker, i;
        for (i = 0; i < locations.length; i++) {
            marker = new google.maps.Marker({
                position: new google.maps.LatLng(locations[i][1], locations[i][2]),
                map: map,
                title: locations[i][0],
                icon: "images/mapiconpost.png"
            });
            google.maps.event.addListener(marker, 'click', (function(marker, i) {
                return function() {
                    infowindow.setContent(locations[i][4]);
                    infowindow.open(map, marker);
                };
            })(marker, i));
        }

    }
}
function CrombFormRenderer() {
    function render() {
        var author = getCookie("signature");
        if (author === null) {
            author = "Anonymous";
        }
        if (crombUser !== null) {
            author = crombUser.username;
        }
        var html = "";
        html += "<div class='cromb'>";
        html += "<form id='postForm' target='hidden' ENCTYPE='multipart/form-data' METHOD='POST' action='servlets/DataManager'>";
        html += "Image: <input type='file' name='file' accept='image/*' value='Select...'/>";
        html += "<br><textarea name='message' maxlength=500 cols=30 rows=4></textarea>";
        if (crombUser !== null) {
            html += "<br>" + author + "<input name='author' type=hidden maxlength=50 value='" + author + "' readonly>";
        } else {
            html += "<br><input name='author' type=text maxlength=50 value='" + author + "'>";
        }
        html += "<input name='action' type=hidden value='post'>";
        html += "<input name='lon' type=hidden value='" + gpsLongitude + "'>";
        html += "<input name='lat' type=hidden value='" + gpsLatitude + "'>";
        html += "<br><input type='button' onclick='submitCrombPostForm();' value='Post'>";
        html += "</form><iframe style='visibility:hidden;display:none' id='postResult' name='hidden'/>";
        //
        return html;
    }
    this.render = render;

}

var watchPost;
function submitCrombPostForm() {
    showWarningPleaseWait("Submitting your post...");
    console.log("Submit...");
    $('#postForm').submit();
    watchPost = setInterval(detectFormCompleted, 1000);
    lastCrombs=undefined;

}
function detectFormCompleted() {
    if ($("#postResult").contents().find("status").length > 0) {
        clearInterval(watchPost);
        console.log("Submit completed");
        setTimeout(showWalletCrombs, 100);
    }
}
function CrombRenderer(cromb,updateFunction) {
    this.cromb = cromb;
    this.update = updateFunction;
    function render() {
        var cromb = this.cromb;
        var update = this.update;
        var call = "";
        if (crombUser !== null) {
            call = "updateCrombLikeCounter(" + cromb.id + ");getCrombs();setTimeout("+update+",500);";
        } else {
            call = 'alert("You have to login to approve");';
        }
        var html = "<div class='cromb'>" + cromb.message + "<div class='likeCounter'><button class='buttonLike' onclick='" + call + "'>" + cromb.likeCounter + "<img width=10 heigth=10 src='images/like.png' alt='Likes'/></button></div><div class='signature'>" + cromb.author + "</div><div class='datetime'>(" + renderDistance(cromb.distance) + ") " + cromb.datetime + "</div></div>";
        return html;
    }
    this.render = render;
}
var secVal1 = 0;
var secVal2 = 0;
function LoginRenderer() {
    function render() {
        var html = "<div class='cromb'>";
        if (crombUser !== null) {
            html += "Email:<br>" + crombUser.email + "<input name='useremail' size=35 id='useremail' type=hidden value='" + crombUser.email + "'>";
            html += "<br>Username:<br><input name='username' size=35 maxlength=35 id='username' type=text value='" + crombUser.username + "'>";
            html += "<br><input  type=button onclick='submitLogout();' value='Logout...'>";
            secVal1 = Math.floor((Math.random() * 10) + 1);
            secVal2 = Math.floor((Math.random() * 10) + 1);
            html += "<br><br>Security Question:<br>" + secVal1 + "+" + secVal2 + "=<input maxlength=2 size=2 type=text id=security>";
            html += "<br><input  type=button onclick='submitResetLogin();' value='Update User'>";
        } else {
            var lastEmail = getCookie("lastemail");
            if (lastEmail === null || lastEmail === undefined) {
                lastEmail = "";
            }
            html += "Email:<br><input name='useremail' size=35 id='useremail' type=email value='" + lastEmail + "'>";
            if (crombUser !== null) {
                html += "<input name='username' size=35 maxlength=35 id='username' type=hidden value='" + crombUser.username + "'>";
            } else {
                html += "<input name='username' size=35 maxlength=35 id='username' type=hidden value='New User'>";
            }
            var pass = getCookie("lastpassword");
            if (pass !== null && pass !== undefined) {
                html += "<br>Password:<br><input size=35 id='userpass' type=password value='" + pass + "'>";
            } else {
                html += "<br>Password:<br><input size=35 id='userpass' type=password>";
            }
            html += "<br><input  type=button onclick='submitLogin();' value='Login...'>";
            secVal1 = Math.floor((Math.random() * 10) + 1);
            secVal2 = Math.floor((Math.random() * 10) + 1);
            html += "<br><br>Security Question:<br>" + secVal1 + "+" + secVal2 + "=<input maxlength=2 size=2 type=text id=security>";
            html += "<br><input  type=button onclick='submitResetLogin();' value='Create/Reset User'>";
        }
        html += "</div>";
        return html;
    }
    this.render = render;
}
function submitResetLogin() {
    var email = $("#useremail").val();
    setCookie("lastemail", email, 360);
    var username = $("#username").val();
    var security = $("#security").val();
    submitLogout();
    if (((secVal1 + secVal2) + "") === security) {
        setTimeout(function() {
            showWarning("Please wait...");
        }, 0);
        if (username === null || username === undefined) {
            username = "New User";
        }
        var status = createlogin(username, email);
        if (status === true) {
            setTimeout(function() {
                showWarning("Check your email inbox for your password...");
            }, 0);
            setTimeout(showWalletLoginForm, 5000);
        } else {
            var text = "User could not be created/updated";
            if (createLoginMessage === "USERNAMEEXISTS") {
                text += "<br>This username already exists";
            }
            setTimeout(function() {
                showWarning(text);
            }, 0);
            setTimeout(showWalletLoginForm, 5000);
        }
    } else {
        showWarning("Incorect security answer...<br>Try again...");
        setTimeout(showWalletLoginForm, 5000);
    }
    updateLogin(("widgetLogin"));
}
function submitLogin() {
    var email = $("#useremail").val();
    setCookie("lastemail", email, 360);
    var pass = $("#userpass").val();
    setCookie("lastpassword", pass, 360);
    var status = login(email, pass);
    if (status === true) {
        showWalletCrombs();
    } else {
        showWarning("Login failed...");
        setTimeout(showWalletLoginForm, 5000);
    }
    updateLogin(("widgetLogin"));
}
function submitLogout() {
    logout();
    updateLogin(("widgetLogin"));
    setTimeout(showWalletLoginForm, 1000);
}
function TagRenderer(tags) {
    this.tags = tags;
    function render() {
        var tags = this.tags;
        var html = "";
        for (var i = 0; i < tags.length; i++) {
            var tag = tags[i];
            var param = '"' + tag.tag + '"';
            var tip = "";
            if (tag.orientation <= 45 && tag.orientation >= -45) {
                tip = "(to the north...)";
            } else if (tag.orientation <= -45 && tag.orientation >= -135) {
                tip = "(to the west...)";
            } else if (tag.orientation <= 135 && tag.orientation >= 45) {
                tip = "(to the east...)";
            } else {
                tip = "(to the south...)";
            }
            html += "<div><div onclick='showWalletTags(" + param + ")' class='tag'>" + tag.tag + "</div><div class='tagDetails'>" + renderDistance(tag.distance) + " " + tip + "</div></div>";
        }
        return html;
    }
    this.render = render;
}
function NewsRenderer(news) {
    this.news = news;
    function render() {
        var news = this.news;
        return "<div class='cromb'>" + news.message + "<div class='datetime'>" + news.datetime + "</div></div>";
    }
    this.render = render;
}
function TopCrombersRenderer(users) {
    this.users = users;
    function render() {
        var users = this.users;
        var html = "<div class='cromb'><div class='title'>Top Cromberz</div>";
        for (var i = 0; i < users.length; i++) {
            html += "<div class='username'>" + users[i].username + "</div><div class='totalpost'>" + users[i].totalPost + " crombz</div>";
        }
        html += "</div>";
        return html;
    }
    this.render = render;
}
var lastTimeCrimeReport = getCookie("lastTimeCrimeReport");
function CrimesRenderer(crimes, global) {
    this.crimes = crimes;
    function render() {
        var crimes = this.crimes;
        var html = "<div class='cromb'><div class='title'>Local (~1 km radius)</div>";

        if (global === true) {
            html = "<div class='cromb'><div class='title'>World Wide</div>";
        }
        html += "<div class='notes'>New feature: Awaiting your inputs...  You can report once a day</div>";
        for (var i = 0; i < crimes.length; i++) {
            if (global === true) {
                var report = "<input class='buttonLike' type=button onclick='submitReportCrime(" + crimes[i].crimeID + ")' value='Report!'/>";
                html += "<div class='username'>" + crimes[i].description + "</div><div class='totalpost'>" + crimes[i].counter + " " + report + "</div>";
            } else {
                html += "<div class='username'>" + crimes[i].description + "</div><div class='totalpost'>" + crimes[i].counter + "</div>";
            }
        }
        html += "</div>";
        return html;
    }
    this.render = render;
}
function EventRenderer(event) {
    this.event = event;
    function render() {
        var event = this.event;
        var html = "<div class='cromb'><div class='eventTitle'>" + event.name + "</div>";
        html += "<div class='eventType'>" + event.description + "</div>";
        html += "<div class='eventDistance'>" + event.distance + "</div>";
        html += "<div class='eventBearing'>" + renderBearing(event.bearing) + "</div>";
        html += "<div class='eventEndingDate'>Ending on " + event.endingDate + "</div>";
        html += "</div>";
        return html;
    }
    this.render = render;
}
function EventPostRenderer(eventTypes) {
    this.eventTypes = eventTypes;
    function render() {
        eventTypes = this.eventTypes;

        var html = "<div class='cromb'><div class='eventTitle'>Add you event</div>";
        html += "<select id='eventType'>";
        for (var i = 0; i < eventTypes.length; i++) {
            html += "<option value='" + eventTypes[i].typeId + "'>" + eventTypes[i].description + "</option>";
        }
        html += "</select><br>Name: <input type=text maxlength=50 id='eventName'>";
        html += "<br>Ending in X days: <input type=text maxlength=2 size=2 id='eventDuration' value='1'>";
        html += "<div class='eventSubmit'><input type=button onclick='submitEvent();' value='Submit'></div>";
        html += "</div>";
        return html;
    }
    this.render = render;
}
function submitEvent() {
    var typeId = $("#eventType").val();
    var name = $("#eventName").val();
    var duration = $("#eventDuration").val();
    postEvent(typeId, name, duration);
    showWarningPleaseWait("Adding event...");
    setTimeout(showWalletEvents, 3000);
}
function submitReportCrime(crimeId) {
    if ((new Date().getTime() - lastTimeCrimeReport) / 1000 > (3600 * 24)) {
        lastTimeCrimeReport = new Date().getTime();
        setCookie("lastTimeCrimeReport", lastTimeCrimeReport, 1);
        reportCrime(crimeId);
        showWarningPleaseWait("Reporting...");
        setTimeout(showWalletCrimes, 3000);
    } else {
        alert("To prevent abuse,\nyou can only report once each 24h...");
    }
}
function GPSInfoRenderer() {
    function render() {
        var html = "<p>This is your current info</p>";
        html += "<li>Longitude: " + gpsLongitude + "</li>";
        html += "<li>Latitude: " + gpsLatitude + "</li>";
        html += "<li>Accuracy: " + gpsAccuracy + "</li>";
        html += "<li>Heading: " + gpsHeading + "</li>";
        html += "<li>Altitude: " + gpsAltitude + "</li>";
        html += "<li>Alt Accuracy: " + gpsAltitudeAccuracy + "</li>";
        html += "<li>Speed: " + gpsSpeed + "</li>";
        html += "<li>Orientation: " + Math.round(orientationAlpha) + " deg</li>";
        html += "<li>Device: " + Math.round(deviceOrientation) + " deg</li>";
        return html;
    }
    this.render = render;
}
function HelpPage1Renderer() {
    function render() {

        var html = "<p>Welcome to Crombz!</p>";
        html += "<p>You can slide left/right on the toolbar to see more...</p>";
        html += "<p>Best experienced with an iPhone/Android smartphone...</p>";
        html += "<li>Crimez: Report local criminal activities</li>";
        html += "<li>News: Latest news from CrombMaster and Top Cromberz</li>";
        html += "<li>Post: Leave a cromb at your current position</li>";
        html += "<li>Distance: Shows you how far is the closest cromb that you cannot see</li>";
        html += "<li>Login: Login with your email and start ranking</li>";
        html += "<li>Counter: Shows you how many crombs were found at your position</li>";
        html += "<li>Compass: GPS Info (Accuracy, Lon, Lat, etc...)</li>";
        html += "<li># (HashTags: Shows HashTags found in your area</li>";
        return html;
    }
    this.render = render;
}
function HelpPage2Renderer() {
    function render() {
        var html = "<p>What is Crombz?</p>";
        html += "<p>A Cromb is a short geo-located message that you can only see when you are at it's location</p>";
        html += "<p>You can leave your own cromb everywhere you want, for your friends or anybody visiting the same spots</p>";
        html += "<p>If you're lucky, you may even find some celebrities or even a mammoth...</p>";
        html += "<p>Make sure that your GPS is enabled for your browser</p>";
        html += "<p>Compass Heading and GPS Info work best when outside</p>";
        html += "<p>Check the accuracy (in Compass), it will tell you if your position is accurate or not</p>";
        html += "<p>Enjoy and don't forget to share with your friends</p>";
        html += "<p>You can follow CrombMaster on <a href='http://twitter.com/CrombMaster' target='twitter' >Twitter</a></p>";
        return html;
    }
    this.render = render;
}

function Card(renderer) {
    this.renderer = renderer;
    function display() {
        $("#wallet").append("<div id='card' class='card'>" + renderer.render() + "</div>");
    }
    this.display = display;

}

function Wallet(id, cards, title) {
    this.cards = cards;
    this.cards.index = 0;
    this.title = title;
//    this.startXTouch = 0;
//    function ontouchstart(e) {
//        startXTouch = e.originalEvent.touches[0].pageX;
//    }
//    this.ontouchstart = ontouchstart;
//    function ontouchend(e) {
//        var delta = startXTouch - e.originalEvent.changedTouches[0].pageX;
//        if ($("#walletnext").length > 0) {
//            if (delta > 100) {
//                next();
//            }
//        }
//        if ($("#walletprevious").length > 0) {
//            if (delta < -100) {
//                previous();
//            }
//        }
//    }
//    this.ontouchend = ontouchend;

    function init(callback) {
		  callback = callback || "";
        $("#mainview").append("<div id='wallet'><div id='wallettitle' class='wallettitle'>" + title + "</div></div>");
//        if (cards.length > 1) {
//            displayNext();
//        }
//        $("#wallet").on('touchstart', ontouchstart);
//        $("#wallet").on('touchend', ontouchend);
        for (var i = 0; i < cards.length; i++) {
            card = cards[i];
            card.display();
        }
    	  $(document).ready(function(){eval(callback)});

    }
    this.init = init;
//    function next() {
//        console.log("Move next...");
//        if (cards.index < cards.length - 1) {
//            cards.index++;
//        }
//        if ($("#walletprevious").length === 0) {
//            displayPrevious();
//        }
//        $("#card").remove();
//        card = cards[cards.index];
//        card.display();
//        $('#card').css('transform', 'translate(450px, 0px) rotate(90deg)');
//        setTimeout(function() {
//            $('#card').css('transform', 'translate(0px, 0px) rotate(0deg)');
//        }, 0);
//        if (cards.index >= cards.length - 1) {
//            $("#walletnext").remove();
//        }
//    }
//    function previous() {
//        console.log("Move previous...");
//        if (cards.index > 0) {
//            cards.index--;
//        }
//        if ($("#walletprevious").length > 0 && cards.index === 0) {
//            $("#walletprevious").remove();
//        }
//        $("#card").remove();
//        card = cards[cards.index];
//        card.display();
//        $('#card').css('transform', 'translate(-400px, 0px) rotate(-90deg)');
//        setTimeout(function() {
//            $('#card').css('transform', 'translate(0px, 0px) rotate(0deg)');
//        }, 0);
//
//        if ($("#walletnext").length === 0 && cards.length > 0) {
//            displayNext();
//        }
//    }
//    this.next = next;
//    this.previous = previous;
//
//    function displayNext() {
//        $("#wallettitle2").append("<div id='walletnext' class='walletnext'>Next</div>");
//        $("#walletnext").click(next);
//    }
//    function displayPrevious() {
//        $("#wallettitle2").append("<div id='walletprevious' class='walletprevious'>Previous</div>");
//        $("#walletprevious").click(previous);
//    }
//    this.displayNext = displayNext;
//    this.displayPrevious = displayPrevious;


}

function renderBearing(bearing) {
    var html = "";
    var b = (bearing + 360.0) % 360;
    var relative = (360 + (b - orientationAlpha)) % 360;
    html += "<img width=50 height=50 style='transform: rotate(" + relative + "deg);-webkit-transform:rotate(" + relative + "deg);' src='images/arrow.png'>";
    return html;
}